﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Caching;
using System.Web.Configuration;
using FluentData;
using Netstars.Core.Cache;
using Netstars.UserCenter.Core.Helper;

namespace Netstars.UserCenter.Dal
{
    /// <summary>
    /// 生成数据库访问对象
    /// </summary>
    public static class DataContext
    {
        #region 获取数据库访问对象
        /// <summary>
        /// 获取数据库访问对象
        /// </summary>
        public static IDbContext DbContext
        {
            get
            {
                //获取Web.config中配置的数据库类型
                string providerName = WebConfigurationManager.AppSettings["IDbProvider"];
                if (string.IsNullOrWhiteSpace(providerName))
                {
                    throw new ArgumentNullException();
                }
                //构建缓存对象
                CacheObject cache = CacheObject.GetInstance("FluentData.IDbProvider");
                //从缓存中获取对象
                IDbProvider provider = cache.GetValue<IDbProvider>(providerName);
                if (provider == null)
                {
                    provider = ReflectionHelper.CreateInstance<IDbProvider>("FluentData", "FluentData", providerName);
                    cache.Insert(providerName, provider);
                }
                return new DbContext().ConnectionStringName("testDBContext", provider);
            }
        } 
        #endregion
    }
}
